package com.enjoy;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(10001));
        System.out.println("accept()方法之前");
        while (true) {
            final Socket socket = serverSocket.accept();

            new Thread(new ServerTask(socket)).start();
        }
    }

    public static class ServerTask implements Runnable {

        private final Socket socket;

        public ServerTask(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try (InputStream inputStream = this.socket.getInputStream(); OutputStream outputStream = this.socket.getOutputStream()) {
                byte[] bytes = new byte[1024 * 10];
                final int i = inputStream.read(bytes);
                if (i > 0) {
                    System.out.println("i = " + i);
                    final String s = new String(bytes);
                    System.out.println(s);
                }
                outputStream.write("服务端收到".getBytes());
                outputStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
